//


#import "AM_HomeAddViewController.h"
#import "AM_HomeAddTableViewCell.h"

//
@interface AM_HomeAddViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/** <#Description#>*/
@property (nonatomic, strong) UITableView *tableView;
/** <#Description#>*/
@property (nonatomic, strong) NSMutableArray *dataArray;
/** <#Description#>*/
@property (nonatomic, strong) AM_HomeAddTableViewCell *cell;
/** <#Description#>*/
@property (nonatomic, copy) NSString *imgUrl;
/** <#Description#>*/
@property (nonatomic, strong) AM_CoreDataView *fmdb;


@end

@implementation AM_HomeAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    _fmdb = [[AM_CoreDataView alloc]initWithCoreData:@"HomeData" modelName:fmdt success:^{} fail:^(NSError * _Nullable error) {}];
    
    [self setnavBatTitle:@"Creat"];
    //
    __weak typeof(self) weakSelf = self;
    [self setupLeftAndwqwRightSetting:@"Save" block:^{
        [weakSelf Save];
    }];
    
    //
    [self.view addSubview:self.tableView];
}

//#pragma mark ----------------- tableViewDelegate ----------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"cellIdentifier";
    _cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!_cell) {
        _cell = [[AM_HomeAddTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
    }
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //
    __weak typeof(self) weakSelf = self;
    _cell.uploadBlock = ^{
        
        [weakSelf selectImages];
    };
    if (_model != nil ) {
        _cell.model = _model;
    }
    
    return _cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kRelativeHeight(10);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

#pragma mark ----------------- 自定义代理 ----------------
//MARK:选择相册
- (void)selectImages
{
    // 弱引用
    __weak typeof(self) weakSelf = self;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {   //打开相册
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate= weakSelf;
        picker.allowsEditing = YES;
        picker.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:picker animated:YES completion:nil];
    }
    
}

//  相册 代理
- (void)imagePickerController:(UIImagePickerController *)picker                     //返回picker选中的图片
didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    
    _cell.IMG.image=newPhoto;    //设置为头像图片
    [picker dismissViewControllerAnimated:YES completion:nil];
    //
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *name  = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    //设置一个图片的存储路径
    _imgUrl = [NSString stringWithFormat:@"%@.png",name] ;
    
    //获取沙盒Documents目录路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES) lastObject];
    //跟文件名组合起来(使用NSString的实例方法stringByAppendingPathComponent: 组成文件的完整路径）
    NSString *imgpath = [docPath stringByAppendingPathComponent:name];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImageJPEGRepresentation(newPhoto, 0.5) writeToFile:imgpath atomically:YES];
    
    
}
//MARK:保存
- (void)Save {
    if (_cell.nameField.text.length <= 0 ||
        _cell.accField.text.length <= 0 ||
        _cell.pwField.text.length <= 0) {
        [AM_ProgressTool showOnlyText:@"数据不能为空"];
        return;
    }
    if (_imgUrl.length <= 0 && _model == nil) {
        [AM_ProgressTool showOnlyText:@"picture不能为空"];
        return;
    }
    //
    NSMutableDictionary *parameter = [NSMutableDictionary new];
    [parameter setObject:_imgUrl = _imgUrl.length <= 0 ?_model.img:_imgUrl forKey:@"img"];
    [parameter setObject:_cell.nameField.text forKey:@"name"];
    [parameter setObject:_cell.accField.text forKey:@"account"];
    [parameter setObject:_cell.pwField.text forKey:@"password"];
    if (_model == nil) {
        [parameter setObject:[UIView am_randomNumber] forKey:@"id"];
        [_fmdb am_insertNewEntity:parameter success:^{
            //
            [self dismissViewControllerAnimated:YES completion:nil];
            
        } fail:^(NSError * _Nullable error) { }];
        
    }else{
        [_fmdb am_updateEntity:parameter key:[NSString stringWithFormat:@"id=%@",_model.id] success:^{
            [self dismissViewControllerAnimated:YES completion:nil];
            
        } fail:^(NSError * _Nullable error) {}];
    }
}


//
#pragma mark ----------------- 懒加载 ----------------
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, UI_NAV_BAR_HEIGHT, kMainScreenWidth, kMainScreenHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate   = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.rowHeight  = kRelativeHeight(150);
        _tableView.separatorColor = [UIColor clearColor];
    }
    return _tableView;
}




- (void)actionBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}


@end
